﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DocumentManagement.Models;

namespace DocumentManagement.Controllers
{
    public class AuthenticationAttribute : FilterAttribute, IAuthorizationFilter
    {
        private PermissionLevel permissionLevel;
        private bool doAndWhenAuth;

        public AuthenticationAttribute() : this( PermissionLevel.None)
        {
        }

        public AuthenticationAttribute(PermissionLevel pl): this(pl, true)
        {
        }

        public AuthenticationAttribute(PermissionLevel pl, bool isAndAuth)
        {
            this.permissionLevel = pl;
            this.doAndWhenAuth = isAndAuth;
        }

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (null == filterContext.HttpContext.Session["uid"])
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                      new RouteValueDictionary {
                          { "controller", "Account" },
                          { "action", "ShowLogin" }
                      }
                    )
                );
            }
            else
            {
                var controller = (BaseController)filterContext.Controller;
                var m = new YaoHuaModel(null);
                    
                controller.AuthenticatedUser = m.GetUserByIdAndPermission(
                    (int)filterContext.HttpContext.Session[Consts.UidSessionKey], permissionLevel, doAndWhenAuth);
            }
        }

        #endregion
    }
}
